//文章控制
const fs = require(`fs`)
const path = require(`path`)
const mysql = require(`mysql`)
const ArticleController = {}
const dbQuery = require(`../model/query.js`)
const { getUnixTime } = require(`../util/tool.js`)

// 只要是一种映射的数据关系，都可以用对象形式来简化if elseif
let statusTextMap = {
    0: `<span class="c-gray">待审核</span>`,
    1: `<span class="c-green">审核通过</span>`,
    2: `<span class="c-red">审核失败</span>`
}

// 统计出分类的文章总数
ArticleController.cateArticleCount = async (req,res)=>{
    let sql = `SELECT
            t2.cate_name,count(t1.id) as count
        FROM
            article t1
        LEFT JOIN category t2 ON t1.cat_id = t2.cate_id
        GROUP BY
            t1.cat_id;`;
    let result = await queryPromise(sql)
    res.json(result)
}

//文章列表
// ArticleController.index = (req, res) => {
//     // //判断是否有session权限
//     // if(!req.session.userInfo){
//     //     res.redirect('/login');
//     //     return;
//     // }
//     //去除session中用户信息
//     let userInfo = JSON.parse(req.session.userInfo);
//     // 1. 编写sql语句
//     let sql = `select t1.*,t2.cate_name from masterpieces1 t1 
//                     left join category t2 on t1.cat_id = t2.cate_id 
//                     where t1.is_delete = 0 order by t1.id desc`;
//     // 2. 执行sql
//     dbQuery(sql).then(rows => {
//         let data = rows.map((item) => {
//             item.Audit_status_text = statusTextMap[item.Audit_status]
//             return item;
//         })
//         // 3. 把查询出来的数据分配到模板引擎中
//         res.render('article-list.html', { articles: data, userInfo })
//     })
// }

ArticleController.index = (req, res) => {
    // 取出session中的用户信息
    let userInfo = JSON.parse(req.session.userInfo || `{}`);

    // 3. 把查询出来的数据分配到模板引擎中
    res.render(`article-list.html`, {
        userInfo
    })

}
// 回收站列表
ArticleController.recyclelist = (req, res) => {
    // 1. 编写sql语句
    let sql = `select t1.*,t2.cate_name from masterpieces1  as t1 
    left join category t2 on t1.cat_id = t2.cate_id 
    where t1.is_delete = 1 order by t1.id desc`;
    // 2. 执行sql
    dbQuery(sql).then(rows => {
        console.log(rows); // [{title,status},{}]
        let data = rows.map((item) => {
            item.Audit_status_text = statusTextMap[item.status]
            return item;
        })
        // 3. 把查询出来的数据分配到模板引擎中
        res.render(`recycle.html`, { articles: data })
    })
}
//永久删除
ArticleController.delete = (req, res) => {
    //1. 接受要删除的文章的id
    let { id, img } = req.query;
    //2. 编写sql语句，删除
    let sql = `delete from masterpieces1 where id = ${id}`;
    dbQuery(sql, (err, result) => {
        // 3.判断结果
        if (result.affectedRows) {
            // 删除成功 ，重定向到首页
            // 删除文章的引用图片

            if (img) {
                let oldpath = path.join(__dirname, `../`, img)
                fs.unlink(oldpath, (err) => {
                    // 静默
                    // console.log('删除成功')
                })
            }

            res.redirect(`/`)
        } else {
            // 删除失败，响应js代码，让浏览器执行
            res.send(`<script>alert('删除失败'); location.href = '/'; </script>`)
        }
    })
}
// ajax永久删除
ArticleController.ajaxdelete = (req, res) => {
    //1. 接受要删除的文章的id
    let { id, img } = req.body;
    //2. 编写sql语句，删除
    let sql = `delete from masterpieces1 where id = ${id}`;
    dbQuery(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            // 删除成功 ，重定向到首页
            // 删除文章的引用图片
            if (img) {
                let oldpath = path.join(__dirname, `../`, img)
                fs.unlink(oldpath, (err) => {
                    // 静默
                    // console.log('删除成功')
                })
            }
            res.json({
                code: 20000,
                message: `succes`
            })

        } else {
            res.json({
                code: -1,
                message: `fail`
            })
        }
    })
}
// 添加文章的表单页面
ArticleController.add = (req, res) => {
    
    // //判断是否有session权限
    // if(!req.session.userInfo){
    //     res.redirect('/login');
    //     return;
    // }
    // 取出所有的分类数据分配到模板中
    let userInfo = JSON.parse(req.session.userInfo || {});
    console.log(userInfo)
    let sql = `select * from category`;

    dbQuery(sql).then(rows => {
        res.render(`add.html`, { cats: rows, userInfo })
    })
}
// 实现数据添加入库
ArticleController.insert = (req, res) => {
    //判断是否有图片
    let imgPath = ``;
    if (req.file) {
        let { originalname, filename } = req.file
        let ext = originalname.substring(originalname.indexOf(`.`));
        //把上传成功的文件进行重命名 
        let oldPath = path.join(__dirname, `../`, `uploads`, filename);
        let newPath = path.join(__dirname, `../`, `uploads`, filename) + ext;
        //记录数据库存放的路径 upload/....png
        imgPath = `uploads/${filename}${ext}`
        console.log(imgPath)
        fs.renameSync(oldPath, newPath)
    }
    let nowTime = getUnixTime()
    let { article, author, cat_id, content, Audit_status } = req.body
    let sql = `insert into masterpieces1(article,author,cat_id,content,img,Audit_status,addtime)
                values('${article}','${author}','${cat_id}','${content}','${imgPath}','${Audit_status}','${nowTime}')`;
    dbQuery(sql).then(result => {
        if (result.affectedRows) {
            res.send(`<script>alert('成功');location.href='/article';</script>`)

        } else {
            res.send(`<script>alert('失败');location.href='/add';</script>`)
        }
    })
}
//文章编辑回显
ArticleController.edit = async (req, res) => {
    //接收参数
    let { id } = req.query;
    let userInfo = JSON.parse(req.session.userInfo);
    let imgPath = ``;
    if (req.file) {
        let { originalname, filename } = req.file
        let ext = originalname.substring(originalname.indexOf(`.`));
        //把上传成功的文件进行重命名 
        let oldPath = path.join(__dirname, `../`, `uploads`, filename);
        let newPath = path.join(__dirname, `../`, `uploads`, filename) + ext;
        //记录数据库存放的路径 upload/....png
        imgPath = `uploads/${filename}${ext}`
        fs.renameSync(oldPath, newPath)
    }
    //编写sql语句 查询当前文章数据分配给模板
    let sql1 = `select * from masterpieces1 where id = ${id}`;
    let sql2 = `select * from category`;
    let data = dbQuery(sql1)
    let cats = dbQuery(sql2)
    let result = await Promise.all([data, cats])
    console.log(result[0][0]);
    res.render(`edit.html`, {
        masterpieces1: result[0][0],
        cats: result[1],
        userInfo
    })  
}
////实现文章更新入库操作
ArticleController.update = async(req, res) => {
    let {formData} = req.body
    let { id, author, article, Audit_status, content, cat_id } = formData
    let update_time = getUnixTime();
    let sql = `update masterpieces1 set author = '${author}',article ='${article}',
    Audit_status='${Audit_status}',content='${content}',cat_id='${cat_id}' where id ='${id}'`;
    let result = await dbQuery(sql)
    if(result.affectedRows){
        res.json({code:10012,message:`编辑成功`})
    }else{
        // res.send('<script>alert("编辑失败");location.href="/";</script>')
        res.json({code:-2,message:`编辑失败`})
    }
}
//文章加入回收站
ArticleController.recycle = async (req, res) => {
    let { id } = req.query;
    let sql = `update masterpieces1 set is_delete = 1 where id = ${id}`;
    let result = await dbQuery(sql)
    if (result.affectedRows) {
        res.redirect(`/article`)
    } else {
        res.send(`<script>alert('加入失败');location.herf='/';</script>`)
    }
}
//文章还原
ArticleController.restore = async (req, res) => {
    let { id } = req.query;
    let sql = `update masterpieces1 set is_delete = 0 where id = ${id}`;
    let result = await dbQuery(sql)
    if (result.affectedRows) {
        res.redirect(`/recyclelist`)
    } else {
        res.send(`<script>alert('还原失败');location.herf='/';</script>`)
    }
}
//展示一个上传文件的表单
ArticleController.addImg = (req, res) => {
    res.render(`addImg.html`)
}
//处理文件上传
ArticleController.upload = (req, res) => {
    console.log(req.file);//接收二进制数据
    let { originalname, filename, destination } = req.file

    let ext = originalname.substring(originalname.indexOf(`.`));
    //把上传成功的文件进行重命名
    let oldPath = path.join(__dirname, `../`, `uploads`, filename);
    let newPath = path.join(__dirname, `../`, `uploads`, filename) + ext;

    fs.renameSync(oldPath, newPath)
    console.log(req.body);
    res.send(`upload success`)
}

// 文章详情查看
ArticleController.detail = (req, res) => {
    let { id } = req.query;
    let sql = `select t1.*,t2.cate_name from masterpieces1 t1 left join category t2 on t1.cat_id = t2.cate_id where t1.id=${id} `
    dbQuery(sql, (err, rows) => {
        // 渲染一个模板
        console.log(rows)
        res.render(`detail.html`, { article: rows[0] })
    })

}

ArticleController.editContent = (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || `{}`);
    res.render(`editContent.html`, { userInfo })
}

ArticleController.updateArtilceContent = async (req, res) => {
    let { id, content } = req.body;
    let sql = `update masterpieces1 set content = '${content}' where id = ${id}`
    let result = await queryPromise(sql)
    res.json({
        code: 20000,
        message: `编辑文章成功`
    })

}

// 获取分页的时候(可以根据文章状态或文章标题)
ArticleController.articleCount = async (req,res)=>{
    let {curr=1,limit=10,title,status} = req.query; // 1   10
    console.log(req.query)
    // 判断是否有查询条件
    let where = ``;
    if(title){
        where += ` and article like '%${title}%'`
    }

    if(status){
        where += ` and Audit_status = ${status}`
    }
    // 查询文章总记录数
        let sql = `select count(*) as count from masterpieces1  where 1 and  is_delete = 0  ${where}`;
    // let result = await queryPromise(sql)
    let offset = (curr - 1) * limit;
    // 查询分页数据
    let sql2 = `select t1.*,t2.cate_name from masterpieces1  as t1 
                     left join category t2 on t1.cat_id = t2.cate_id 
                     where 1 and  is_delete = 0 ${where}
                     order by t1.id desc 
                     limit ${offset},${limit}`;
        // let result1 = await dbQuery(sql)  
        // let result2 = await dbQuery(sql2)
        // console.log(result1,result2)  
    // let result2 = await queryPromise(sql2)
    // 并行 
    let result = await Promise.all([dbQuery(sql),dbQuery(sql2)])
    // console.log(result); // [[{count:50}],[{},{},{}]]
    res.json({
        count:result[0][0].count,
        data: result[1]
    })

}



module.exports = ArticleController;